package com.frejoys.app.controller;

import cn.hutool.core.util.StrUtil;
import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.common.IdDto;
import com.frejoys.common.dto.common.OrderSnDto;
import com.frejoys.common.dto.order.OrderUserPageDto;
import com.frejoys.common.dto.order.OrderPlaceDto;
import com.frejoys.common.dto.order.PayMoneyDto;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.request.ThreadContext;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.vo.app.StoreIdAndOrderSnVo;
import com.frejoys.common.vo.order.UserOrderInfoVo;
import com.frejoys.common.vo.order.UserOrderPageVo;
import com.frejoys.common.vo.pay.AliH5PayVo;
import com.frejoys.common.vo.pay.OrderSnWxJsPayVo;
import com.frejoys.common.vo.pay.WxJsPayVo;
import com.frejoys.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author wangzhicheng
 * @version 1.0
 * @date 2024/4/18 16:28
 */
@Tag(name = "订单管理", description = "订单管理")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixApp)
@Authorization(Authority.Private)
public class OrderController {

    private final RedissonClient redissonClient;

    private final OrderService orderService;

    @Operation(summary = "微信商品下单js支付")
    @PostMapping("/order/confirm")
    public Result<OrderSnWxJsPayVo> wxOrderConfirm(@RequestBody @Validated OrderPlaceDto dto){

        OrderSnWxJsPayVo vo = null;

        RLock lock = redissonClient.getLock(CacheKeyUtil.orderPayLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                vo = orderService.wxOrderConfirm(RequestUtil.userId(), dto);

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success(vo);
    }

    @Operation(summary = "微信直接下单js支付")
    @PostMapping("/order/payConfirm")
    public Result<OrderSnWxJsPayVo> orderPayConfirm(@RequestBody @Validated PayMoneyDto dto){

        if (dto.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new GeneralException(HttpStatus.orderPayMoneyError);
        }

        OrderSnWxJsPayVo vo = null;

        RLock lock = redissonClient.getLock(CacheKeyUtil.orderPayLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                vo = orderService.wxPayOrderConfirm(RequestUtil.userId(), dto);

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success(vo);
    }

    @Operation(summary = "支付宝商品下单js支付")
    @PostMapping("/order/alipay/h5")
    public Result<AliH5PayVo> aliOrderH5(@RequestBody @Validated OrderPlaceDto dto){

        AliH5PayVo vo = null;

        RLock lock = redissonClient.getLock(CacheKeyUtil.orderPayLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                String content = orderService.aliOrderH5(RequestUtil.userId(), dto);
                if (StrUtil.isNotEmpty(content)) {
                    vo = new AliH5PayVo();
                    vo.setContent(content);
                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success(vo);
    }

    @Operation(summary = "支付宝直接下单js支付")
    @PostMapping("/order/alipay/payH5")
    public Result<AliH5PayVo> aliOrderPayH5(@RequestBody @Validated PayMoneyDto dto){

        if (dto.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new GeneralException(HttpStatus.orderPayMoneyError);
        }

        AliH5PayVo vo = null;

        RLock lock = redissonClient.getLock(CacheKeyUtil.orderPayLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                String content = orderService.aliOrderPayH5(RequestUtil.userId(), dto);
                if (StrUtil.isNotEmpty(content)) {
                    vo = new AliH5PayVo();
                    vo.setContent(content);
                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success(vo);
    }


    @Operation(summary = "申请订单退款")
    @PostMapping("/order/refund")
    public Result orderRefund(@RequestBody @Validated IdDto dto){
        RLock lock = redissonClient.getLock(CacheKeyUtil.orderRefundLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                orderService.orderRefund(RequestUtil.userId(), dto.getId());

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }


    @Operation(summary = "订单转换积分")
    @PostMapping("/order/score")
    public Result orderScore(@RequestBody @Validated IdDto dto){
        RLock lock = redissonClient.getLock(CacheKeyUtil.orderScoreLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                orderService.orderScore(RequestUtil.userId(), dto.getId());

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    /**
     * 分页查询订单
     */
    @Operation(summary = "分页查询订单")
    @PostMapping("/order/pageOrderList")
    public Result<List<UserOrderPageVo>> pageOrderList(@RequestBody @Validated OrderUserPageDto dto) {
        return Result.success(orderService.pageOrderList(dto, RequestUtil.userId()));
    }

    /**
     * 查询订单详情
     */
    @Operation(summary = "查询订单详情")
    @PostMapping("/order/getInfo")
    public Result<UserOrderInfoVo> getInfoByUser(@RequestBody @Validated IdDto idDto) {
        return Result.success(orderService.getInfoByUser(idDto));
    }

    @Operation(summary = "根据订单号查询是否支付")
    @PostMapping("/order/getPayStatus")
    public Result<StoreIdAndOrderSnVo> getPayStatus(@RequestBody @Validated OrderSnDto dto) {
        return Result.success(orderService.getPayStatus(dto));
    }
}
